package wuaipojie

import (
	"context"
	"gitee.com/kaylee595/gkaylee/kerr"
	"github.com/PuerkitoBio/goquery"
	"github.com/robertkrimen/otto/ast"
	"github.com/robertkrimen/otto/parser"
	"net/http"
	"strings"
)

func (c *Client) Check(ctx context.Context) error {
	url := "https://www.52pojie.cn/home.php?mod=task&do=apply&id=2&referer=%2F"
	resp := c.httpClient.Get(url).Do(ctx)
	if resp.Err != nil {
		return kerr.WrapTraceStack(resp.Err)
	}
	if resp.StatusCode != http.StatusOK {
		return kerr.WrapTraceStack(NewErrReq(resp, kerr.New("status code must be 200")))
	}
	dom, err := goquery.NewDocumentFromReader(resp.Body)
	if err != nil {
		return kerr.WrapTraceStack(NewErrReq(resp, err))
	}
	msgNode := dom.Find("#messagetext > p").First()
	msgNode.Find("script").Remove() // remove setTimeout("window.location.href ='home.php?mod=task&item=new';", 3000);
	ret := msgNode.Text()
	if !strings.HasPrefix(ret, "恭喜您，任务已完成") {
		if strings.Contains(dom.Find("noscript").Text(), "Please enable JavaScript and refresh the page.") {
			// var LZ = '32030', LJ = '17609', LE = 'csIhzWVjDYa/gmeGP+q5KC1b6UXxtNRHAnTfwikolZSB2Qud7J9p4rvF0EM38yLO';
			e := &ErrNeedVerifyWaf{}
			program, err := parser.ParseFile(nil, "", dom.Find("script").Text(), 0)
			if err != nil {
				return kerr.WrapTraceStack(err)
			}
		loop:
			for _, dec := range program.DeclarationList {
				declaration, ok := dec.(*ast.VariableDeclaration)
				if !ok {
					continue
				}
				for _, expression := range declaration.List {
					literal, ok := expression.Initializer.(*ast.StringLiteral)
					if !ok {
						continue
					}
					switch expression.Name {
					case "LZ":
						e.LZ = literal.Value
					case "LJ":
						e.LJ = literal.Value
					case "LE":
						e.LE = literal.Value
					}
					if e.LZ != "" && e.LJ != "" && e.LE != "" {
						break loop
					}
				}
			}
			if e.LJ == "" || e.LZ == "" || e.LE == "" {
				return kerr.WrapTraceStack(NewErrReq(resp, kerr.New("get waf params failed")))
			}
			e.UserAgent = resp.Request.Headers.Get("User-Agent")
			return kerr.WrapTraceStack(e)
		}
		if ret == "" {
			return kerr.WrapTraceStack(NewErrReq(resp, kerr.New("#messagetext > p not found")))
		} else if ret == "您需要先登录才能继续本操作" {
			return kerr.WrapTraceStack(ErrNeedLogin)
		} else {
			return kerr.WrapTraceStack(ErrCheck(ret))
		}
	}
	return nil
}
